package lc;

import org.junit.Test;

public class Ex468 {
    class Solution1 {
        public String validIPAddress(String IP) {
            String s = IP;
            if (s.length() < 7 || s.startsWith(".") || s.endsWith(".")
                    || s.startsWith(":") || s.endsWith(":")) return "Neither";
            if (IP.contains(".")) {
                String[] ss = s.split("\\.");
                return checkIPV4(ss) ? "IPv4" : "Neither";
            } else if (IP.contains(":")) {
                String[] ss = s.split(":");
                return checkIPV6(ss) ? "IPv6" : "Neither";
            } 
            return  "Neither";
        }
    
        public boolean checkIPV4(String[] ss) {
            if (ss.length != 4) return false;
            for (int i = 0; i < ss.length; i++) {
                if (parse(ss[i]) < 0) {
                    return false;
                }
            }
            return true;
        }
    
        public int parse(String s) {
            char[] cs = s.toCharArray();
            int len = cs.length;
            if (len == 0 || len > 1 && cs[0] == '0') return -1;
            int res = 0;
            for (int i = 0; i < len; i++) {
                if (cs[i] >= '0' && cs[i] <= '9') {
                    res = res * 10 + cs[i] - '0';
                } else {
                    return -1;
                }
            }
            return res < 256 ? res : -1;
        }
    
        public boolean checkIPV6(String[] ss) {
            int len = ss.length;
            if (len != 8) return false;
            for (int i = 0; i < len; i++) {
                if (!check(ss[i])) {
                    return false;
                }
            }
            return true;
        }
    
        public boolean check(String s) {
            int len = s.length();
            // if (len == 1) {
            //     return s.equals("0");
            // }
            if (len > 4 || len == 0) {
                return false;
            }
            char[] cs = s.toCharArray();
            for (int i = 0; i < len; i++) {
                if (!(cs[i] >= '0' && cs[i] <= '9' || cs[i] >= 'a' && cs[i] <= 'f'||
                 cs[i] >= 'A' && cs[i] <= 'F' )) return false;
            }
            return true;
        }
    }

    @Test
    public void test() {
        Solution s = new Solution();
        System.out.println(s.validIPAddress("192.0.0.1"));        
    }

    class Solution {
        public String validIPAddress(String queryIP) {
            return "";
        }
    }
}
